<template>
  <div>
    <h2>商品管理</h2>
    <el-card>
      <div style="margin-bottom: 16px; display: flex; gap: 12px;">
        <el-button type="primary" @click="openAddDialog">新增商品</el-button>
        <el-input v-model="search.keyword" placeholder="商品名关键词" clearable style="width: 200px" />
        <el-button type="primary" @click="fetchList">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>
      <el-table :data="productList" border style="width: 100%" @row-click="handleRowClick">
        <el-table-column prop="id" label="ID" width="60" />
        <el-table-column prop="name" label="商品名" />
        <el-table-column prop="categoryId" label="分类ID" width="90" />
        <el-table-column prop="brand" label="品牌" width="100" />
        <el-table-column prop="price" label="价格" width="100" />
        <el-table-column prop="stock" label="库存" width="80" />
        <el-table-column prop="mainImage" label="主图" width="100">
          <template #default="scope">
            <el-image v-if="scope.row.mainImage" :src="scope.row.mainImage" style="width:40px;height:40px" fit="cover" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button size="small" @click.stop="showDetail(scope.row)">详情</el-button>
            <el-button size="small" @click.stop="openEditDialog(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click.stop="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top: 16px; text-align: right;">
        <el-pagination
          background
          layout="prev, pager, next, jumper, ->, total"
          :total="total"
          :page-size="pageSize"
          :current-page="pageNum"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑商品弹窗 -->
    <el-dialog v-model="editDialog" :title="editMode === 'add' ? '新增商品' : '编辑商品'" width="500px">
      <el-form :model="editForm" label-width="90px">
        <el-form-item label="商品名">
          <el-input v-model="editForm.name" />
        </el-form-item>
        <el-form-item label="分类ID">
          <el-input v-model="editForm.categoryId" />
        </el-form-item>
        <el-form-item label="品牌">
          <el-input v-model="editForm.brand" />
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model="editForm.price" type="number" />
        </el-form-item>
        <el-form-item label="库存">
          <el-input v-model="editForm.stock" type="number" />
        </el-form-item>
        <el-form-item label="主图">
          <el-input v-model="editForm.mainImage" />
        </el-form-item>
        <el-form-item label="图片(逗号分隔)">
          <el-input v-model="editForm.images" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="editForm.description" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSaveProduct">保存</el-button>
      </template>
    </el-dialog>

    <!-- 商品详情弹窗 -->
    <el-dialog v-model="detailDialog" title="商品详情" width="500px">
      <el-descriptions :column="1" border v-if="detail">
        <el-descriptions-item label="ID">{{ detail.id }}</el-descriptions-item>
        <el-descriptions-item label="商品名">{{ detail.name }}</el-descriptions-item>
        <el-descriptions-item label="分类ID">{{ detail.categoryId }}</el-descriptions-item>
        <el-descriptions-item label="品牌">{{ detail.brand }}</el-descriptions-item>
        <el-descriptions-item label="价格">{{ detail.price }}</el-descriptions-item>
        <el-descriptions-item label="库存">{{ detail.stock }}</el-descriptions-item>
        <el-descriptions-item label="描述">{{ detail.description }}</el-descriptions-item>
        <el-descriptions-item label="主图">
          <el-image v-if="detail.mainImage" :src="detail.mainImage" style="width:60px;height:60px" fit="cover" />
        </el-descriptions-item>
        <el-descriptions-item label="图片">
          <div v-if="detail.images && detail.images.length">
            <el-image
              v-for="(img, idx) in detail.images"
              :key="idx"
              :src="img"
              style="width:40px;height:40px;margin-right:4px"
              fit="cover"
            />
          </div>
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailDialog = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { getProductList, getProductDetail, addProduct, updateProduct, deleteProduct } from '../api/product'
import { ElMessage, ElMessageBox } from 'element-plus'

const productList = ref([])
const total = ref(0)
const pageNum = ref(1)
const pageSize = ref(10)
const search = reactive({
  keyword: ''
})

const detailDialog = ref(false)
const detail = ref(null)

const editDialog = ref(false)
const editMode = ref('add') // 'add' or 'edit'
const editForm = reactive({
  id: null,
  name: '',
  categoryId: '',
  brand: '',
  price: '',
  stock: '',
  mainImage: '',
  images: '',
  description: ''
})

const fetchList = async () => {
  try {
    const params = {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      keyword: search.keyword || undefined
    }
    const res = await getProductList(params)
    if (res.data && res.data.list) {
      productList.value = res.data.list
      total.value = res.data.total
    }
  } catch (e) {
    ElMessage.error('获取商品列表失败')
    console.error(e)
  }
}

const handlePageChange = (val) => {
  pageNum.value = val
  fetchList()
}

const resetSearch = () => {
  search.keyword = ''
  pageNum.value = 1
  fetchList()
}

const showDetail = async (row) => {
  try {
    const res = await getProductDetail(row.id)
    if (res.data) {
      // 兼容 images 字段为 JSON 字符串或数组
      let imgs = []
      if (typeof res.data.images === 'string') {
        try { imgs = JSON.parse(res.data.images) } catch { imgs = [] }
      } else if (Array.isArray(res.data.images)) {
        imgs = res.data.images
      }
      detail.value = { ...res.data, images: imgs }
      detailDialog.value = true
    }
  } catch (e) {
    ElMessage.error('获取商品详情失败')
  }
}

const handleRowClick = (row) => {
  showDetail(row)
}

const openAddDialog = () => {
  editMode.value = 'add'
  Object.assign(editForm, {
    id: null,
    name: '',
    categoryId: 0,
    brand: '',
    price: '',
    stock: '',
    mainImage: '',
    images: '',
    description: ''
  })
  editDialog.value = true
}

const openEditDialog = (row) => {
  editMode.value = 'edit'
  Object.assign(editForm, {
    ...row,
    images: Array.isArray(row.images) ? row.images.join(',') : (row.images || '')
  })
  editDialog.value = true
}

const handleSaveProduct = async () => {
  try {
    const payload = {
      ...editForm,
      // categoryId 必须为数字且不能为空
      categoryId: Number(editForm.categoryId) || 0,
      // 后端Product.images字段为String，前端需传字符串
      images: typeof editForm.images === 'string'
        ? editForm.images
        : Array.isArray(editForm.images)
          ? editForm.images.join(',')
          : ''
    }
    if (editMode.value === 'add') {
      await addProduct(payload)
      ElMessage.success('添加成功')
    } else {
      await updateProduct(editForm.id, payload)
      ElMessage.success('更新成功')
    }
    editDialog.value = false
    fetchList()
  } catch (e) {
    ElMessage.error('保存失败')
  }
}

const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该商品吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    await deleteProduct(row.id)
    ElMessage.success('删除成功')
    fetchList()
  }).catch(() => {})
}

onMounted(() => {
  fetchList()
})
</script>